package com.yonyou.brigade.order_center.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.BriFlightOrder;
import com.yonyou.brigade.order_center.model.BriHotelOrder;
import com.yonyou.brigade.order_center.model.BriTrainOrder;
import com.yonyou.brigade.order_center.service.*;
import com.yonyou.brigade.order_center.dao.ExpenseStatusMapper;
import com.yonyou.brigade.order_center.model.ExpenseStatus;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.util.resultutil.Msg;
import com.yonyou.brigade.util.resultutil.ResultUtil;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

@Service
public class ExpneseStatusServiceImpl extends ServiceImpl<ExpenseStatusMapper , ExpenseStatus> implements IExpenseStatusService {

    private static Logger logger = LoggerFactory.getLogger(ExpneseStatusServiceImpl.class);

    @Autowired
    private ExpenseStatusMapper expenseStatusMapper;

    @Autowired
    private IThirdOrderService thirdOrderService;

    @Autowired
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    private IBaseDocService baseDocService;

    @Autowired
    private IUserCenterService userCenterService;

    @Override
    public Msg getOrderStatusByPK(JSONObject param) {
        JSONObject rs = new JSONObject();
        if (!CollectionUtils.isEmpty(param)) {
            List list = (List)param.get("ybz_pks");
            if(!CollectionUtils.isEmpty(list)){
                List<ExpenseStatus> status = expenseStatusMapper.selectList(new EntityWrapper<ExpenseStatus>()
                        .in("ybz_pk",list).and().eq("valid" , 1)
                );
                rs.put("statuList", status);
                return ResultUtil.success(rs);
            }
            list = (List)param.get("nc_pks");
            if(!CollectionUtils.isEmpty(list)){
                List<ExpenseStatus> status = expenseStatusMapper.selectList(new EntityWrapper<ExpenseStatus>()
                        .in("nc_pk",list).and().eq("valid" , 1)
                );
                return ResultUtil.success(status);
            }
        }
        return ResultUtil.paraError();
    }

    @Override
    @Transactional
    public Msg setStatus(JSONArray param, String tenant) {
        JSONObject rs = new JSONObject();
        if (!CollectionUtils.isEmpty(param)) {
            for(int i=0;i<param.size();i++){
                JSONObject par = param.getJSONObject(i);
                String ybzPk = par.getString("ybz_pk") == null ? "" : par.getString("ybz_pk");
                String ncPk = par.getString("nc_pk") == null ? "" : par.getString("nc_pk");
                if (StringUtil.isEmpty(ybzPk) && StringUtil.isEmpty(ncPk)){
                    throw new BusinessException("单据号不能为空");
                }
                String orderNo = par.getString("orderno");
                if (StringUtil.isEmpty(orderNo)){
                    throw new BusinessException("订单号不能为空");
                }
                String billNum = par.getString("billnum");
                String bxState = par.getString("bx_state");
                String voucherNo = par.getString("voucherNo");
                Integer payState = par.getInteger("payState");
                ExpenseStatus reimbursedByOrder = null;
                String orderClassification = "";
                //查询该订单是否是在报销中或已报销
                List<ExpenseStatus> reimbursedByOrderList = getRelationByOrderNo(orderNo);
                if (reimbursedByOrderList.size() > 0){
                    reimbursedByOrder = reimbursedByOrderList.get(0);
                    orderClassification = reimbursedByOrder.getOrder_classification();
                }
                Set<String> relationOrderNoList = getRelationOrderNoList(orderClassification, orderNo, tenant);
                relationOrderNoList.add(orderNo);

                for (String relaionOrderNo : relationOrderNoList) {
                    //查询该订单是否是在报销中或已报销
                    if (!orderNo.equals(relaionOrderNo)){
                        reimbursedByOrderList = getRelationByOrderNo(relaionOrderNo);
                        if (reimbursedByOrderList.size() > 0){
                            reimbursedByOrder = reimbursedByOrderList.get(0);
                        }
                    }
                    setStatus(tenant, relaionOrderNo, ybzPk, ncPk, reimbursedByOrder, billNum, bxState, voucherNo, payState, par);
                }
            }
            return ResultUtil.success(rs);
        }
        return ResultUtil.paraError();
    }

    private void setStatus(String tenantId, String orderNo, String ybzPk, String ncPk, ExpenseStatus reimbursedByOrder, String billNum, String bxState, String voucherNo, Integer payState, JSONObject par){
        //查询当前要更新的单据订单报销状态关联关系
        List<ExpenseStatus> list = new ArrayList<>();
        JSONArray fillBackCLYHParam = new JSONArray();
        Wrapper<ExpenseStatus> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        wrapper.eq("valid", 1);
        if (StringUtil.isNotEmpty(ybzPk)){
            wrapper.eq("ybz_pk", ybzPk);
            list = this.selectList(wrapper);
            if (list.size() < 1 && StringUtil.isNotEmpty(ncPk)){
                wrapper = new EntityWrapper<>();
                wrapper.eq("order_no", orderNo);
                wrapper.eq("valid", 1);
                wrapper.eq("nc_pk", ncPk);
                list = this.selectList(wrapper);
            }
        }else if (StringUtil.isNotEmpty(ncPk)){
            wrapper.eq("nc_pk", ncPk);
            list = this.selectList(wrapper);
        }
        if (list.size() < 1){
//            throw new BusinessException("报销单与订单未关联");
            return;
        }
        for (ExpenseStatus expenseStatus : list) {
            //如果订单状态是报销中或已报销，则只有单据PK一致才能修改
            if (reimbursedByOrder != null && !ybzPk.equals(reimbursedByOrder.getYbz_pk()) && !ncPk.equals(reimbursedByOrder.getNc_pk())){
                if (orderNo.contains("_")){
                    orderNo = orderNo.split("_")[0];
                }
                throw new BusinessException("无法修改，订单号" + orderNo + "与报销单号" + reimbursedByOrder.getBillnum() + "不匹配");
            }
            if (StringUtil.isNotEmpty(billNum)){
                expenseStatus.setBillnum(billNum);
            }
            if (StringUtil.isNotEmpty(bxState)){
                expenseStatus.setBx_state(bxState);
            }
            if (voucherNo != null){
                expenseStatus.setVoucherNo(voucherNo);
            }
            if (payState != null){
                expenseStatus.setPayState(payState);
            }
            expenseStatus.setNcExpensePk(!StringUtils.isEmpty(par.getString("ncExpensePk")) ? par.getString("ncExpensePk") : "");
            expenseStatus.setVoucherType(!StringUtils.isEmpty(par.getString("voucherType")) ? par.getString("voucherType") : "");
            expenseStatus.setVoucherTypeName(!StringUtils.isEmpty(par.getString("voucherTypeName")) ? par.getString("voucherTypeName") : "");
            if (par.get("voucherDateTime") != null) {
                try {
                    expenseStatus.setVoucherDateTime(DateUtils.longToDateTime(par.getLong("voucherDateTime")));
                } catch (Exception e) {
                    logger.error("voucherDateTime格式化失败：" + e.getMessage());
                    expenseStatus.setVoucherDateTime("");
                }
            } else {
                expenseStatus.setVoucherDateTime("");
            }
            expenseStatus.setModifiedTime(new Date());
            JSONObject clyhParam = new JSONObject();
            clyhParam.put("orderNo", orderNo);
            clyhParam.put("orderType", expenseStatus.getOrder_classification());
            clyhParam.put("bxStatus", bxState);
            clyhParam.put("expenseStatus", expenseStatus);
            fillBackCLYHParam.add(clyhParam);
        }
        if (list.size() > 0){
            this.updateBatchById(list);
            thirdOrderService.clyhOrdersStateBackFill(tenantId, fillBackCLYHParam);
        }
    }


    @Override
    @Transactional
    public Msg addConnection(JSONArray params, Boolean isRollBack, String tenant) {
        JSONObject rs = new JSONObject();
        JSONArray fillBackCLYHParam = new JSONArray();
        Set<String> orderSet = new HashSet<>();
        if(!CollectionUtils.isEmpty(params)){
            for(int i=0;i<params.size();i++){
                JSONObject jsonObject = params.getJSONObject(i);
                String orderNo = jsonObject.getString("orderno");
                if (StringUtil.isEmpty(orderNo)){
                    throw new BusinessException("订单号不能为空");
                }
                if (orderSet.contains(orderNo)){
                    continue;
                }
                String orderType = jsonObject.getString("order_classification");

                Set<String> relationOrderNoList = getRelationOrderNoList(orderType, orderNo, tenant);
                relationOrderNoList.add(orderNo);

                //处理订单及其关联订单
                for (String relationOrderNo : relationOrderNoList) {
                    orderSet.add(relationOrderNo);
                    //如果订单已被报销
                    ExpenseStatus relationObj = hasOrderReimbursed(relationOrderNo);
                    if (relationObj != null){
                        if (orderNo.contains("_")){
                            orderNo = orderNo.split("_")[0];
                        }
                        //比较数据。修改逻辑，因为被关联的报销单不能再被选到，现在认为关联同一个订单的一定是同一个报销单， 如果ybz_pk和nc_pk同时不为空时才去比较是否报销单PK是否一致
                        compareData(relationObj, jsonObject, orderNo);
                        this.updateById(relationObj);
                    }else {
                        addConnection(fillBackCLYHParam, jsonObject, relationOrderNo, orderType, tenant);
                    }
                }
            }
//            thirdOrderService.clyhOrdersStateBackFill(tenant, fillBackCLYHParam);
            rs.put("reimbursedOrderNos", null);
            return ResultUtil.success(rs);
        }
        return ResultUtil.paraError();
    }

    private void compareData(ExpenseStatus relationObj, JSONObject jsonObject, String orderNo) {
        String relYbzPk = relationObj.getYbz_pk();
        String ybzPk = jsonObject.getString("ybz_pk");
        if (StringUtil.isNotEmpty(relYbzPk)){
            if (StringUtil.isNotEmpty(ybzPk)){
                if (!ybzPk.equals(relYbzPk)){
                    throw new BusinessException("订单号"+ orderNo +"已被报销单号" + relationObj.getBillnum() + "关联");
                }
            }else {
                jsonObject.put("ybz_pk", relYbzPk);
            }
        }else {
            relationObj.setYbz_pk(ybzPk);
        }
        String relNcPk = relationObj.getNc_pk();
        String ncPk = jsonObject.getString("nc_pk");
        if (StringUtil.isNotEmpty(relNcPk)){
            if (StringUtil.isNotEmpty(ncPk)){
                if (!relNcPk.equals(ncPk)){
                    throw new BusinessException("订单号"+ orderNo +"已被报销单号" + relationObj.getBillnum() + "关联");
                }
            }else {
                jsonObject.put("nc_pk", relNcPk);
            }
        }else {
            relationObj.setNc_pk(ncPk);
        }
        if (StringUtil.isEmpty(jsonObject.getString("billnum")) && StringUtil.isNotEmpty(relationObj.getBillnum())){
            jsonObject.put("billnum", relationObj.getBillnum());
        }
        if (StringUtil.isEmpty(relationObj.getBillnum()) && StringUtil.isNotEmpty(jsonObject.getString("billnum"))){
            relationObj.setBillnum(jsonObject.getString("billnum"));
        }

        if (StringUtil.isEmpty(relationObj.getDjlxpk()) && StringUtil.isNotEmpty(jsonObject.getString("djlxpk"))){
            relationObj.setDjlxpk(jsonObject.getString("djlxpk"));
        }
        if (StringUtil.isEmpty(jsonObject.getString("djlxpk")) && StringUtil.isNotEmpty(relationObj.getDjlxpk())){
            jsonObject.put("djlxpk", relationObj.getDjlxpk());
        }

        if (StringUtil.isEmpty(jsonObject.getString("djlxname")) && StringUtil.isNotEmpty(relationObj.getDjlxname())){
            jsonObject.put("djlxname", relationObj.getDjlxname());
        }
        if (StringUtil.isEmpty(relationObj.getDjlxname()) && StringUtil.isNotEmpty(jsonObject.getString("djlxname"))){
            relationObj.setDjlxname(jsonObject.getString("djlxname"));
        }
        relationObj.setModifiedTime(new Date());
    }

    private void addConnection(JSONArray fillBackCLYHParam, JSONObject jsonObject, String orderNo, String orderType, String tenant){
        String bxState = jsonObject.getString("bx_state");
        ExpenseStatus expenseStatus = getExpeseStatus(jsonObject, orderNo, orderType, bxState, tenant);
        this.insert(expenseStatus);
        JSONObject param = new JSONObject();
        param.put("orderNo", orderNo);
        param.put("orderType", orderType);
        param.put("bxStatus", bxState);
        fillBackCLYHParam.add(param);
    }
    private ExpenseStatus getExpeseStatus(JSONObject jsonObject, String orderNo, String orderType, String bxState, String tenant){
        String userId = "";
        JSONObject tenantInfoById = userCenterService.getTenantInfoById(tenant);
        if (tenantInfoById != null && "1".equals(tenantInfoById.getString("status"))) {
            if (tenantInfoById.getJSONObject("tenant") != null) {
                String adminPhone = tenantInfoById.getJSONObject("tenant").getString("tenantTel");
                UcUserDto completeUcUserDtoByPhone = userCenterService.getCompleteUcUserDtoByPhone(adminPhone, tenant);
                userId = completeUcUserDtoByPhone != null ? completeUcUserDtoByPhone.getUserId() : "";
            }
        }
        ExpenseStatus expenseStatus = new ExpenseStatus();
        expenseStatus.setValid(1);
        expenseStatus.setOrder_no(orderNo);
        expenseStatus.setOrder_classification(orderType);
        expenseStatus.setBx_state(bxState);
        expenseStatus.setBillnum(jsonObject.getString("billnum"));
        expenseStatus.setBxUserName(jsonObject.getString("bxUserName"));
        expenseStatus.setBxUserCode(jsonObject.getString("bxUserCode"));
        expenseStatus.setYbz_pk(jsonObject.getString("ybz_pk"));
        expenseStatus.setNc_pk(jsonObject.getString("nc_pk"));
        expenseStatus.setDjlxpk(jsonObject.getString("djlxpk"));
        expenseStatus.setDjlxname(jsonObject.getString("djlxname"));
        expenseStatus.setSysType(jsonObject.getString("sysType"));
        expenseStatus.setTenant(tenant);
        expenseStatus.setModifiedTime(new Date());
        expenseStatus.setOrgPk(jsonObject.getString("orgPk"));
        expenseStatus.setDeptPk(jsonObject.getString("deptPk"));
        expenseStatus.setOrgName(jsonObject.getString("orgName"));
        expenseStatus.setDeptName(jsonObject.getString("deptName"));
        if (StringUtils.isEmpty(jsonObject.getString("orgName"))) {
            Map<String, String> resultMap = baseDocService.getOrgByOsType(tenant, userId, jsonObject.getString("orgPk"), jsonObject.getString("ostype"));
            expenseStatus.setOrgName(CollectionUtils.isEmpty(resultMap) ? "" : resultMap.get("name"));
            expenseStatus.setOrgPk(CollectionUtils.isEmpty(resultMap) ? "" : resultMap.get("code"));
        }
        if (StringUtils.isEmpty(jsonObject.getString("deptName"))) {
            Map<String, String> resultMap = baseDocService.getOrgByOsType(tenant, userId, jsonObject.getString("deptPk"), jsonObject.getString("ostype"));
            expenseStatus.setDeptName(CollectionUtils.isEmpty(resultMap) ? "" : resultMap.get("name"));
            expenseStatus.setDeptPk(CollectionUtils.isEmpty(resultMap) ? "" : resultMap.get("code"));
        }
        expenseStatus.setNcExpensePk(jsonObject.getString("ncExpensePk"));
        return expenseStatus;
    }

    /**
     * 根据订单号查询出关联订单
     * @param orderClassification
     * @param orderNo
     * @param tenant
     * @return
     */
    private Set<String>  getRelationOrderNoList(String orderClassification, String orderNo, String tenant){
        HashSet<String> resultList = new HashSet<>();
        if (orderClassification == null) {
            return resultList;
        }
        switch (orderClassification){
            case "flight":
                Wrapper<BriFlightOrder> wrapper =  new EntityWrapper<>();
                wrapper.eq(BriFlightOrder.ORDER_NO, orderNo);
                wrapper.eq(BriFlightOrder.TENANT, tenant);
                BriFlightOrder flightOrder = briFlightOrderService.selectOne(wrapper);
                if (flightOrder != null){
                    List<BriFlightOrder> briFlightOrderList = briFlightOrderService.getRelationOrdersV2(orderNo,flightOrder.getParentOrderNo(), flightOrder.getFromType(), tenant);
                    for (BriFlightOrder briFlightOrder : briFlightOrderList) {
                        resultList.add(briFlightOrder.getOrderNo());
                    }
                }
                break;
            case "hotel":
                Wrapper<BriHotelOrder> hotelWrapper = new EntityWrapper<>();
                hotelWrapper.eq(BriHotelOrder.ORDER_NO, orderNo);
                hotelWrapper.eq(BriHotelOrder.TENANT, tenant);
                BriHotelOrder hotelOrder = briHotelOrderService.selectOne(hotelWrapper);
                if (hotelOrder != null) {
                    List<BriHotelOrder> hotelOrderList = briHotelOrderService.getRelationOrdersV2(orderNo, hotelOrder.getParentOrderNo(), hotelOrder.getFromType(), tenant);
                    for (BriHotelOrder briHotelOrder : hotelOrderList) {
                        resultList.add(briHotelOrder.getOrderNo());
                    }
                }
                break;
            case "train":
                Wrapper<BriTrainOrder> trainWrapper = new EntityWrapper<>();
                trainWrapper.eq(BriTrainOrder.ORDER_NO, orderNo);
                trainWrapper.eq(BriTrainOrder.TENANT, tenant);
                BriTrainOrder briTrainOrder = briTrainOrderService.selectOne(trainWrapper);
                if (briTrainOrder != null) {
                    List<BriTrainOrder> briTrainOrderList = briTrainOrderService.getRelationOrdersV2(orderNo, briTrainOrder.getParentOrderNo(), briTrainOrder.getFromType(), tenant);
                    for (BriTrainOrder trainOrder : briTrainOrderList) {
                        resultList.add(trainOrder.getOrderNo());
                    }
                }
                break;
        }
        return resultList;
    }

    /**
     * 订单是否被报销或在报销中
     * @param orderNo
     * @return
     */
    @Override
    public ExpenseStatus hasOrderReimbursed(String orderNo){
        List<ExpenseStatus> expenseStatusList = getRelationByOrderNo(orderNo);
        if (expenseStatusList.size() > 0) {
            return expenseStatusList.get(0);
        }
        return null;
    }

    /**
     * 根据订单编号获取报销中的订单的关联记录
     * @param orderNo
     * @return
     */
    private List<ExpenseStatus> getRelationByOrderNo(String orderNo){
        ArrayList<String> arrayList = new ArrayList<>();
        Wrapper<ExpenseStatus> wrapper = new EntityWrapper<>();
        wrapper.eq("order_no", orderNo);
        wrapper.eq("valid", 1);
        return this.selectList(wrapper);
    }

    @Override
    @Transactional
    public Msg cancelConnection(JSONArray params, Boolean isRollBack, String tenant) {
        JSONObject rs = new JSONObject();
        Set<String> reimbursedOrderNos = new HashSet<>();
        JSONArray fillBackCLYHParam = new JSONArray();
        if(!CollectionUtils.isEmpty(params)){
            for(int i=0;i<params.size();i++) {
                JSONObject jsonObject = params.getJSONObject(i);
                Map<String , Object> map = new HashMap();
                String orderNo = jsonObject.getString("orderno");
                map.put("orderno" , orderNo);
                String ybzPk = jsonObject.getString("ybz_pk");
                String ncPk = jsonObject.getString("nc_pk");
                ExpenseStatus relationObj = hasOrderReimbursed(orderNo);
                if (StringUtil.isNotEmpty(orderNo) && relationObj != null){
                    String pk = StringUtil.isNotEmpty(relationObj.getYbz_pk()) ? relationObj.getYbz_pk() : relationObj.getNc_pk();
                    if ( (StringUtil.isNotEmpty(ybzPk) && StringUtil.isNotEmpty(relationObj.getYbz_pk()) && !ybzPk.equals(relationObj.getYbz_pk()))
                        || (StringUtil.isNotEmpty(ncPk) && StringUtil.isNotEmpty(relationObj.getNc_pk()) && !ncPk.equals(relationObj.getNc_pk()))){
                        if (orderNo.contains("_")){
                            orderNo = orderNo.split("_")[0];
                        }
                        throw new BusinessException("无法取消，订单"+ orderNo +"与报销单号" + relationObj.getBillnum() + "不匹配");
                    }
                }
                if(StringUtil.isNotEmpty(ybzPk)){
                    map.put("ybz_pk" , ybzPk);
                }
                if(StringUtil.isNotEmpty(ncPk)){
                    map.put("nc_pk" , ncPk);
                }
                if (StringUtil.isNotEmpty(ybzPk) || StringUtil.isNotEmpty(ncPk)){
                    expenseStatusMapper.deleteStatus(map);

                    //拼装回传差旅壹号参数，处理关联订单
                    if (StringUtil.isNotEmpty(orderNo) && relationObj != null){
                        Set<String> relationOrderNoList = getRelationOrderNoList(relationObj.getOrder_classification(), orderNo, tenant);
                        relationOrderNoList.add(orderNo);
                        for (String relationOrderNo : relationOrderNoList) {
                            if (!orderNo.equals(relationOrderNo)) {
                                map.put("orderno" , relationOrderNo);
                                expenseStatusMapper.deleteStatus(map);
                            }
                            JSONObject param = new JSONObject();
                            param.put("orderNo", relationOrderNo);
                            param.put("orderType", relationObj.getOrder_classification());
                            param.put("bxStatus", 0);
                            relationObj.setBx_state("0");
                            param.put("expenseStatus", relationObj);
                            fillBackCLYHParam.add(param);
                        }
                    }
                }
            }
            thirdOrderService.clyhOrdersStateBackFill(tenant, fillBackCLYHParam);
            if (reimbursedOrderNos.size() > 0){
                rs.put("reimbursedOrderNos", reimbursedOrderNos);
            }
            return ResultUtil.success(rs);
        }
        return ResultUtil.paraError();
    }

    @Transactional
    @Override
    public Msg updateConnection(JSONArray params, Boolean isRollBack, String tenant) {
        JSONObject rs = new JSONObject();
        Set<String> reimbursedOrderNos = new HashSet<>();
        JSONArray fillBackCLYHParam = new JSONArray();
        Set<String> orderNoSet = new HashSet<>();
        Map<String, ExpenseStatus> deleteMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(params)) {
            Set<String> expenseYbzPks = new CopyOnWriteArraySet<>();
            Set<String> expenseNcPks = new CopyOnWriteArraySet<>();
            JSONArray addEsList = new JSONArray();
//            addEsList.addAll(params);
//            for (int i = 0; i < params.size(); i++) {
//                orderNoSet.add(params.getJSONObject(i).getString("orderno"));
//            }
            for (Object param : params) {
                JSONObject paramJSON = JSONObject.parseObject(JSON.toJSONString(param));
                String ybzPk = paramJSON.getString("ybz_pk");
                String ncPk = paramJSON.getString("nc_pk");
                String orderNo = paramJSON.getString("orderno");
                // 特殊处理处理凭证生成时间
                if (paramJSON.get("voucherDateTime") != null) {
                    try {
                        Long voucherDateTime = paramJSON.getLong("voucherDateTime");
                        paramJSON.put("voucherDateTime", com.yonyou.brigade.util.operateutil.DateUtils.longToDateTime(voucherDateTime));
                    } catch (Exception e) {
                        logger.error("voucherDateTime格式化失败：" + e.getMessage());
                        paramJSON.put("voucherDateTime", "");
                    }
                } else {
                    paramJSON.put("voucherDateTime", "");
                }
                param = paramJSON;
                if (orderNoSet.contains(orderNo)){
                    continue;
                }
                if (!StringUtil.isEmpty(orderNo)) {
                    addEsList.add(param);
                    orderNoSet.add(orderNo);
                    String orderClassification = paramJSON.getString("order_classification");
                    Set<String> relationOrderNoList = getRelationOrderNoList(orderClassification, orderNo, tenant);
                    relationOrderNoList.add(orderNo);
                    for (String relationOrderNo : relationOrderNoList) {
                        if (!orderNo.equals(relationOrderNo) && !orderNoSet.contains(relationOrderNo)){
                            JSONObject relationJson = (JSONObject) paramJSON.clone();
                            relationJson.put("orderno", relationOrderNo);
                            orderNoSet.add(relationOrderNo);
                            addEsList.add(relationJson);
                        }
                        updateConnection(relationOrderNo, ncPk, ybzPk, expenseYbzPks, expenseNcPks, orderClassification, paramJSON);
                    }
                }
            }
            if (!CollectionUtils.isEmpty(expenseYbzPks)) {
                Wrapper<ExpenseStatus> wrapper = new EntityWrapper<>();
                wrapper.in("ybz_pk", expenseYbzPks);
                List<ExpenseStatus> list = this.selectList(wrapper);
                for (ExpenseStatus expenseStatus : list) {
                    deleteMap.put(expenseStatus.getOrder_no(), expenseStatus);
                }
                expenseStatusMapper.deleteStatusByYbzPks(expenseYbzPks);
            }
            if (!CollectionUtils.isEmpty(expenseNcPks)) {
                Wrapper<ExpenseStatus> wrapper = new EntityWrapper<>();
                wrapper.in("nc_pk", expenseNcPks);
                List<ExpenseStatus> list = this.selectList(wrapper);
                for (ExpenseStatus expenseStatus : list) {
                    deleteMap.put(expenseStatus.getOrder_no(), expenseStatus);
                }
                expenseStatusMapper.deleteStatusByNcPks(expenseNcPks);
            }
            List<ExpenseStatus> expenseStatuses = JSONArray.parseArray(JSON.toJSONString(addEsList), ExpenseStatus.class);
            if (!CollectionUtils.isEmpty(expenseStatuses)) {
                for (ExpenseStatus expenseStatus : expenseStatuses) {
                    expenseStatus.setValid(1);
                    expenseStatus.setTenant(tenant);
                    if (deleteMap.containsKey(expenseStatus.getOrder_no())){
                        deleteMap.remove(expenseStatus.getOrder_no());
                        //存在或新增的关联关系，回传差旅壹号更改订单报销状态
                        JSONObject param = new JSONObject();
                        param.put("orderNo", expenseStatus.getOrder_no());
                        param.put("orderType", expenseStatus.getOrder_classification());
                        param.put("bxStatus", expenseStatus.getBx_state());
                        param.put("expenseStatus", expenseStatus);
                        fillBackCLYHParam.add(param);
                    }
                }
                this.insertBatch(expenseStatuses);
            }
            //被删除掉的关联关系，回传差旅壹号将订单报销状态改为未报销
            if (!CollectionUtils.isEmpty(deleteMap)) {
                for (String key : deleteMap.keySet()) {
                    ExpenseStatus deleteRelation = deleteMap.get(key);
                    JSONObject param = new JSONObject();
                    param.put("orderNo", deleteRelation.getOrder_no());
                    param.put("orderType", deleteRelation.getOrder_classification());
                    param.put("bxStatus", 0);
                    param.put("expenseStatus", deleteRelation);
                    fillBackCLYHParam.add(param);
                }
            }
            if (reimbursedOrderNos.size() > 0){
                rs.put("reimbursedOrderNos", reimbursedOrderNos);
            }
            thirdOrderService.clyhOrdersStateBackFill(tenant, fillBackCLYHParam);
            return ResultUtil.success(rs);
        }
        return ResultUtil.paraError();
    }

    private void updateConnection(String orderNo, String ncPk, String ybzPk, Set<String> expenseYbzPks, Set<String> expenseNcPks, String orderClassification, JSONObject paramJSON){
        //判断是否订单在报销中或已报销，并且报销单和新的报销单不一致
        List<ExpenseStatus> reimbursedByOrderList = getRelationByOrderNo(orderNo);
        if (StringUtil.isNotEmpty(orderNo) && reimbursedByOrderList != null && reimbursedByOrderList.size() > 0){
            String oldYbzPk = reimbursedByOrderList.get(0).getYbz_pk();
            String oldNCPk = reimbursedByOrderList.get(0).getNc_pk();
            if (StringUtil.isNotEmpty(oldNCPk) && StringUtil.isNotEmpty(ncPk) && !oldNCPk.equals(ncPk)) {
                if (orderNo.contains("_")){
                    orderNo = orderNo.split("_")[0];
                }
                throw new BusinessException("订单"+ orderNo +"被报销单号" + reimbursedByOrderList.get(0).getBillnum() + "关联");
            }
            if (StringUtil.isNotEmpty(oldYbzPk) && StringUtil.isNotEmpty(ybzPk) && !oldYbzPk.equals(ybzPk)){
                if (orderNo.contains("_")){
                    orderNo = orderNo.split("_")[0];
                }
                throw new BusinessException("订单"+ orderNo +"被报销单号" + reimbursedByOrderList.get(0).getBillnum() + "关联");
            }
        }
        if (!StringUtils.isEmpty(ybzPk)){
            expenseYbzPks.add(ybzPk);
        }
        if (!StringUtils.isEmpty(ncPk)) {
            expenseNcPks.add(ncPk);
        }
        //取出原关联中的单据PK，补充到新的关联关系
        Wrapper<ExpenseStatus> wrapper = new EntityWrapper<>();
        wrapper.eq("valid", 1);
        wrapper.eq("order_no", orderNo);
        wrapper.eq("order_classification", orderClassification);
        if (StringUtil.isEmpty(ybzPk)){
            wrapper.eq("nc_pk", ncPk);
            List<ExpenseStatus> expenseStatuses = this.selectList(wrapper);
            if (expenseStatuses.size() > 0 && StringUtil.isNotEmpty(expenseStatuses.get(0).getYbz_pk())) {
                ExpenseStatus expenseStatus = expenseStatuses.get(0);
                compareData(expenseStatus, paramJSON, orderNo);
                paramJSON.put("ybz_pk", expenseStatus.getYbz_pk());
            }
        }else {
            wrapper.eq("ybz_pk", ybzPk);
            List<ExpenseStatus> expenseStatuses = this.selectList(wrapper);
            if (expenseStatuses.size() > 0 && StringUtil.isEmpty(ncPk)) {
                ExpenseStatus expenseStatus = expenseStatuses.get(0);
                compareData(expenseStatus, paramJSON, orderNo);
                paramJSON.put("nc_pk", expenseStatus.getNc_pk());
            }
        }
    }
}
